package com.example.easycharge.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.easycharge.entity.Alert;
import com.example.easycharge.error.AlertNotFoundError;
import com.example.easycharge.repository.AlertRepository;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

@Tag(name = "警报管理接口组")
@RestController
@RequestMapping("alert")
public class AlertController {
    @Autowired
    private AlertRepository alertRepository;

    @Operation(description = "新增一个警报")
    @PostMapping("/admin")
    public JSONObject addNewAlert(@RequestBody Alert alert) {
        alert.setAlertDate(new Date());
        alert.setSolved(false);
        alert.setSolveDate(null);
        alert = alertRepository.saveAndFlush(alert);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("message", "新增警报成功");
        jsonObject.put("detail", alert);
        return jsonObject;
    }

    @Operation(description = "解决报警信息")
    @PutMapping("/admin/{alertId}")
    public JSONObject solveAlert(@PathVariable("alertId") long alertId) throws AlertNotFoundError {
        if (alertRepository.countAlertByAlertId(alertId) == 0) {
            throw new AlertNotFoundError();
        }
        alertRepository.solveAlert(alertId);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("message", "警报解除成功");
        return jsonObject;
    }

    @Operation(description = "根据是否解决来分页获取所有报警信息")
    @GetMapping("admin/{solved}/{page}/{pageNum}/{asc}")
    public Page<Alert> getAllUnsolvedAlert(@PathVariable("page") int page,
                                           @PathVariable("pageNum") int pageNum,
                                           @PathVariable("asc") boolean asc,
                                           @PathVariable("solved") boolean solved) {
        Pageable pageable = PageRequest.of(page - 1, pageNum, asc ? Sort.Direction.ASC : Sort.Direction.DESC, "alertDate");
        return alertRepository.findAllBySolved(pageable, solved);
    }

    @Operation(description = "根据报警编号来删除报警信息")
    @DeleteMapping("admin/{alertId}")
    public JSONObject deleteAlterById(@PathVariable("alertId") long alertId) throws AlertNotFoundError {
        if (alertRepository.countAlertByAlertId(alertId) == 0) {
            throw new AlertNotFoundError();
        }
        alertRepository.deleteById(alertId);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("message", "警报删除成功");
        return jsonObject;
    }
}
